<template>
  <div class="collection-page">
    <!-- 滚动进度条 -->
    <div class="fixed top-0 left-0 w-full h-1 z-50">
      <div ref="progressBar" class="h-full bg-indigo-600 origin-left transform scale-x-0"></div>
    </div>

    <!-- 英雄区块 -->
    <section ref="heroSection" class="hero">
      <!-- SVG 遮罩图案 -->
      <div ref="maskContainer" class="mask-container">
        <svg
          ref="heroMask"
          class="mask-svg"
          :style="{
            transform: `scale(${state.mask.currentScale})`,
            opacity: state.mask.opacity,
          }"
          viewBox="0 0 18000 9000"
          preserveAspectRatio="xMidYMid slice"
        >
          <path
            fill-rule="evenodd"
            clip-rule="evenodd"
            d="M18000 0H0V9000H18000V0ZM12179 4017.76L12289.3 4359.76C12294.6 4376.38 12289 4394.76 12275.1 4405.51L12246.1 4428.13C12234.3 4437.38 12220.1 4443.01 12205.1 4444.51L12002.2 4464.76C12002.2 4464.76 11912.2 4458.38 11918.6 4593.51C11925.1 4728.63 11899.4 4825.13 11770.6 4966.76C11644.2 5105.76 10841.2 5648.38 9989.5 5698.13C9956.75 5700.01 9924.88 5688.01 9901.62 5664.88C9825.15 5588.76 9760.49 5464.22 9690.6 5329.62C9540.04 5039.62 9365.21 4702.88 8995.62 4702.88C8626.01 4702.88 8451.18 5039.62 8300.61 5329.64C8230.74 5464.21 8166.09 5588.73 8089.62 5664.88C8066.38 5688.13 8034.5 5700.01 8001.75 5698.13C7150.12 5648.38 6347 5105.76 6220.62 4966.76C6091.88 4825.13 6066.25 4728.63 6072.62 4593.51C6079.12 4458.38 5989 4464.76 5989 4464.76L5786.12 4444.51C5771.25 4443.01 5757 4437.38 5745.12 4428.13L5716.12 4405.51C5702.25 4394.76 5696.62 4376.51 5702 4359.76L5812.5 4017.76C5821.88 3988.88 5848.75 3969.26 5879.12 3969.26H6256.88C6276.75 3969.26 6296.38 3964.13 6313.62 3954.01C6340.27 3938.27 6370.44 3917.11 6406.19 3892.03C6672.83 3704.99 7250.18 3300.01 8995.75 3300.01C10741.4 3300.01 11318.8 3705.02 11585.5 3892.04C11621.2 3917.11 11651.4 3938.27 11678 3954.01C11695.1 3964.13 11714.8 3969.26 11734.8 3969.26H12112.4C12142.8 3969.26 12169.6 3988.88 12179 4017.76ZM7950.38 3613.38C7950.38 3664.01 8418.5 3705.13 8995.75 3705.13C9573.12 3705.13 10041.1 3664.01 10041.1 3613.38C10041.1 3562.76 9573.12 3521.63 8995.75 3521.63C8418.38 3521.63 7950.38 3562.76 7950.38 3613.38Z"
            fill="white"
          />
        </svg>
      </div>

      <!-- 加载动画 -->
      <div
        v-if="!state.video.loaded || state.video.error"
        class="absolute inset-0 z-40 bg-black/90 flex items-center justify-center"
      >
        <div class="text-white text-center">
          <template v-if="!state.video.error">
            <div
              class="w-16 h-16 border-4 border-white border-t-transparent rounded-full animate-spin mb-4"
            ></div>
            <div class="text-xl">
              视频加载中...{{
                videoLoadAttempts > 0 ? `(重试 ${videoLoadAttempts}/${maxRetries})` : ''
              }}
            </div>
          </template>
          <template v-else>
            <div class="text-xl">
              <svg
                class="w-16 h-16 mx-auto mb-4 text-red-500"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
                />
              </svg>
              <p>视频加载失败</p>
              <button
                @click="tryPlayVideo"
                class="mt-4 px-6 py-2 bg-white/20 hover:bg-white/30 rounded-lg transition-colors"
              >
                重试加载
              </button>
            </div>
          </template>
        </div>
      </div>

      <div class="hero-content relative z-20 text-white text-center max-w-5xl px-4">
        <h1
          ref="heroTitle"
          class="text-4xl md:text-6xl lg:text-8xl font-bold leading-tight opacity-0"
        >
          <span class="block overflow-hidden relative">
            <span
              class="block transform translate-y-full"
              ref="heroText1"
              style="will-change: transform"
              >CRUSH</span
            >
          </span>
          <span class="block overflow-hidden relative">
            <span
              class="block transform translate-y-full"
              ref="heroText2"
              style="will-change: transform"
              >ORDINARY</span
            >
          </span>
        </h1>
        <p
          ref="heroSubtitle"
          class="mt-8 text-xl md:text-2xl opacity-0 transform translate-y-10"
          style="will-change: transform, opacity"
        >
          突破界限，定义未来
        </p>
      </div>

      <div ref="parallaxWrapper" class="absolute inset-0 z-10">
        <video
          ref="heroVideo"
          class="absolute inset-0 w-full h-full object-cover scale-110"
          :class="{ 'opacity-0': !state.video.loaded }"
          autoplay
          muted
          loop
          playsinline
          poster="https://images.unsplash.com/photo-1469474968028-56623f02e42e?q=80&w=1920&h=1080&fit=crop"
          @loadeddata="handleVideoLoad"
          @error="handleVideoError"
          preload="auto"
        >
          <source :src="currentVideoSource" type="video/mp4" />
        </video>
        <!-- 渐变叠加层 -->
        <div
          class="absolute inset-0 bg-gradient-to-b from-black/60 via-black/40 to-black/60 mix-blend-multiply transition-opacity duration-1000"
          :class="{ 'opacity-0': !state.video.loaded }"
        ></div>
      </div>
    </section>

    <!-- 购物车指示器 -->
    <div class="fixed top-4 right-4 z-50">
      <button
        @click="showCart = true"
        class="relative bg-black text-white p-3 rounded-full hover:bg-gray-800 transition-colors"
      >
        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z"
          />
        </svg>
        <span
          v-if="cartCount > 0"
          class="absolute -top-2 -right-2 bg-red-500 text-white text-xs w-5 h-5 flex items-center justify-center rounded-full"
        >
          {{ cartCount }}
        </span>
      </button>
    </div>

    <!-- 产品展示区块 -->
    <section class="products">
      <ProductSpotlight
        v-for="(product, index) in products"
        :key="product.id"
        :title="product.name"
        :description="product.description"
        :image-url="product.image"
        :price="product.price"
        :specs="product.specs"
        :reverse="index % 2 !== 0"
        :button-text="product.buttonText"
        @open-details="handleOpenDetails(product)"
        @add-to-cart="handleAddToCart(product)"
      />
    </section>

    <!-- 购物车侧边栏 -->
    <div
      v-if="showCart"
      class="fixed inset-0 bg-black bg-opacity-50 z-50"
      @click="showCart = false"
    >
      <div
        class="fixed right-0 top-0 bottom-0 w-96 max-w-full bg-white p-6 transform translate-x-0 transition-transform duration-300"
        @click.stop
      >
        <div class="flex justify-between items-center mb-6">
          <h3 class="text-xl font-bold">购物车</h3>
          <button @click="showCart = false" class="text-gray-500 hover:text-black">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          </button>
        </div>

        <div v-if="cartItems.length === 0" class="text-center text-gray-500 py-8">购物车是空的</div>

        <div v-else class="space-y-4">
          <div
            v-for="(item, index) in cartItems"
            :key="index"
            class="flex items-center gap-4 p-4 bg-gray-50 rounded-lg"
          >
            <img :src="item.image" :alt="item.name" class="w-20 h-20 object-cover rounded" />
            <div class="flex-1">
              <h4 class="font-medium">{{ item.name }}</h4>
              <p class="text-sm text-gray-500">￥{{ item.price }}</p>
            </div>
            <button @click="removeFromCart(index)" class="text-red-500 hover:text-red-600">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
                />
              </svg>
            </button>
          </div>

          <div class="border-t pt-4">
            <div class="flex justify-between items-center mb-4">
              <span class="font-medium">总计</span>
              <span class="font-bold"
                >￥{{ cartItems.reduce((sum, item) => sum + item.price, 0) }}</span
              >
            </div>
            <button
              class="w-full bg-black text-white py-3 rounded-lg hover:bg-gray-800 transition-colors"
            >
              结算
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 滚动画廊 -->
    <section ref="gallerySection" class="gallery relative h-[300vh]">
      <div
        class="sticky-wrapper sticky top-0 h-screen overflow-hidden"
        style="contain: paint layout; will-change: transform"
      >
        <div class="absolute inset-0 bg-black/95 transition-opacity duration-500"></div>

        <!-- 画廊轨道 -->
        <div class="absolute inset-0 flex items-center justify-center">
          <div
            ref="galleryTrack"
            class="relative w-full h-full perspective-1000"
            style="will-change: transform"
          >
            <div
              v-for="(image, index) in gallery"
              :key="image.id"
              class="gallery-item absolute inset-0 flex items-center justify-center"
              :style="{
                zIndex: index,
                transform: `translate3d(0, 0, ${-index * 50}px)`,
                willChange: 'transform, opacity',
              }"
            >
              <div
                class="relative w-[80vw] max-w-[1200px] mx-auto transform-gpu backface-visibility-hidden"
              >
                <div
                  class="aspect-[16/9] overflow-hidden rounded-xl"
                  style="transform: translateZ(0)"
                >
                  <img
                    :ref="
                      (el) => {
                        galleryImages.value[index] = el
                      }
                    "
                    :src="image.url"
                    :srcset="`${image.url}?w=800 800w, ${image.url}?w=1200 1200w, ${image.url}?w=1600 1600w`"
                    sizes="(max-width: 800px) 800px, (max-width: 1200px) 1200px, 1600px"
                    :alt="image.alt"
                    width="1600"
                    height="900"
                    class="w-full h-full object-cover transition-transform duration-1000 ease-out transform-gpu"
                    :class="{ 'scale-110 blur-sm opacity-0': !state.gallery.loadStatus[index] }"
                    loading="lazy"
                    decoding="async"
                  />
                </div>
                <div
                  :ref="
                    (el) => {
                      galleryCaptions.value[index] = el
                    }
                  "
                  class="caption-wrapper absolute left-0 bottom-0 w-full p-12 bg-gradient-to-t from-black/90 via-black/50 to-transparent opacity-0 transform translate-y-10"
                  style="transform: translate3d(0, 0, 0); backface-visibility: hidden"
                >
                  <div class="transform-gpu">
                    <h3 class="text-6xl font-bold mb-6 text-white">{{ image.alt }}</h3>
                    <p class="text-2xl text-gray-300 font-light">探索非凡设计的极限</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- 返回顶部按钮 -->
    <button
      v-show="showBackToTop"
      @click="scrollToTop"
      class="fixed bottom-8 right-8 z-50 bg-black text-white w-12 h-12 rounded-full flex items-center justify-center hover:bg-gray-800 transition-colors"
    >
      <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path
          stroke-linecap="round"
          stroke-linejoin="round"
          stroke-width="2"
          d="M5 10l7-7m0 0l7 7m-7-7v18"
        />
      </svg>
    </button>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import gsap from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger'
import ProductSpotlight from '../components/ProductSpotlight.vue'

gsap.registerPlugin(ScrollTrigger)

// 确保全局可用
if (typeof window !== 'undefined') {
  window.gsap = gsap
  window.ScrollTrigger = ScrollTrigger
}

// 画廊数据
const galleryData = [
  {
    id: 1,
    url: 'https://images.unsplash.com/photo-1511499767150-a48a237f0083?q=80&w=1920&h=1080&fit=crop',
    alt: '时尚墨镜展示',
  },
  {
    id: 2,
    url: 'https://images.unsplash.com/photo-1473496169904-658ba7c44d8a?q=80&w=1920&h=1080&fit=crop',
    alt: '运动墨镜特写',
  },
  {
    id: 3,
    url: 'https://images.unsplash.com/photo-1580250864656-cd501faa9c76?q=80&w=1920&h=1080&fit=crop',
    alt: '生活方式展示',
  },
]

// 状态管理
const state = reactive({
  // 视频状态
  video: {
    loaded: false,
    error: false,
    attempts: 0,
    maxRetries: 3,
    source: '/videos/Video_hero_AFA_D.mp4',
  },
  // 遮罩状态
  mask: {
    initialScale: 0.2,
    maxScale: 8.0,
    currentScale: 0.2,
    opacity: 0.92,
  },
  // 画廊状态
  gallery: {
    loadStatus: {},
    loadProgress: 0,
    items: [...galleryData],
    images: [],
    captions: [],
  },
  // 性能状态
  performance: {
    fps: 0,
    mode: 'high',
    lowPerformanceCount: 0,
  },
  // UI状态
  ui: {
    showBackToTop: false,
    showCart: false,
    cartItems: [],
    cartCount: 0,
  },
})

// 视频相关的响应式数据
const videoLoadAttempts = ref(0)
const maxRetries = ref(3)
const currentVideoSource = computed(() => state.video.source)

// 商品数据
const products = ref([
  {
    id: 1,
    name: '轻奢太阳镜',
    description: '采用高科技材料，轻盈舒适，防紫外线，时尚设计。',
    image: 'https://images.unsplash.com/photo-1511499767150-a48a237f0083?w=800',
    price: 1999,
    specs: ['100% UV防护', '轻量级钛合金镜框', '防反光镀膜', '含收纳盒'],
    buttonText: '查看详情',
  },
  {
    id: 2,
    name: '运动墨镜',
    description: '专业运动防护，防风防尘，适合户外运动。',
    image: 'https://images.unsplash.com/photo-1473496169904-658ba7c44d8a?w=800',
    price: 1299,
    specs: ['防风设计', '防滑鼻托', '可更换镜片', '运动束带'],
    buttonText: '了解更多',
  },
])

// 购物车相关的方法
const handleOpenDetails = (product) => {
  console.log('打开产品详情:', product)
}

const handleAddToCart = (product) => {
  state.ui.cartItems.push(product)
  state.ui.cartCount = state.ui.cartItems.length
  state.ui.showCart = true
}

const removeFromCart = (index) => {
  state.ui.cartItems.splice(index, 1)
  state.ui.cartCount = state.ui.cartItems.length
}

// 引用管理
const refs = {
  heroSection: ref(null),
  heroVideo: ref(null),
  heroText1: ref(null),
  heroText2: ref(null),
  heroMask: ref(null),
  heroSubtitle: ref(null),
  parallaxWrapper: ref(null),
  maskContainer: ref(null),
  gallerySection: ref(null),
  galleryTrack: ref(null),
  progressBar: ref(null),
  galleryImages: ref([]),
  galleryCaptions: ref([]),
}

// 图片预加载和初始化
const initGallery = () => {
  nextTick(() => {
    state.gallery.items.forEach((_, index) => {
      state.gallery.loadStatus[index] = false
    })

    refs.galleryImages.value = new Array(state.gallery.items.length).fill(null)
    refs.galleryCaptions.value = new Array(state.gallery.items.length).fill(null)
  })
}

// 性能优化相关的函数
const performanceOptimizer = {
  memory: () => {
    const visibleImages = refs.galleryImages.value.filter((img) => {
      const rect = img?.getBoundingClientRect()
      return rect && rect.top < window.innerHeight + 1000 && rect.bottom > -1000
    })

    refs.galleryImages.value.forEach((img) => {
      if (img && !visibleImages.includes(img)) {
        img.src = ''
        img.srcset = ''
      }
    })
  },

  disableParallax: () => {
    if (refs.parallaxWrapper.value) {
      refs.parallaxWrapper.value.style.transform = 'none'
    }
  },

  disableAnimations: () => {
    document.body.classList.add('reduce-motion')
    refs.galleryImages.value.forEach((img) => {
      if (img) {
        img.style.transition = 'none'
      }
    })
  },

  apply: () => {
    const prevMode = state.performance.mode

    if (state.performance.mode === 'high') {
      state.performance.mode = 'medium'
      performanceOptimizer.disableParallax()
      showPerformanceHint('medium')
    } else if (state.performance.mode === 'medium') {
      state.performance.mode = 'low'
      performanceOptimizer.disableAnimations()
      showPerformanceHint('low')
    }

    if (prevMode !== state.performance.mode) {
      console.log(`性能模式从 ${prevMode} 切换至 ${state.performance.mode}`)
      performanceOptimizer.memory()
    }
  },
}

// 视频处理方法
const handleVideoLoad = () => {
  state.video.loaded = true
  state.video.error = false
  videoLoadAttempts.value = 0

  // 确保视频循环播放
  if (refs.heroVideo.value) {
    refs.heroVideo.value.play().catch((err) => {
      console.warn('自动播放失败:', err)
      state.video.error = true
    })
  }
}

const handleVideoError = () => {
  videoLoadAttempts.value++
  if (videoLoadAttempts.value < maxRetries.value) {
    tryPlayVideo()
  } else {
    state.video.error = true
  }
}

const tryPlayVideo = async () => {
  if (!refs.heroVideo.value) return

  try {
    state.video.error = false
    await refs.heroVideo.value.load()
    await refs.heroVideo.value.play()
    handleVideoLoad()
  } catch (err) {
    console.warn('视频播放失败:', err)
    handleVideoError()
  }
}

// 滚动到顶部方法
const scrollToTop = () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth',
  })
}

// 图片加载处理
const handleImageLoad = (index) => {
  if (typeof index === 'number') {
    state.gallery.loadStatus[index] = true
    updateImageLoadProgress()
  }
}

// 更新加载进度
const updateImageLoadProgress = () => {
  const totalImages = state.gallery.items.length
  const loadedImages = Object.values(state.gallery.loadStatus).filter(Boolean).length
  state.gallery.loadProgress = (loadedImages / totalImages) * 100
}

// 滚动处理
const throttle = (func, limit) => {
  let inThrottle
  return (...args) => {
    if (!inThrottle) {
      func.apply(null, args)
      inThrottle = true
      setTimeout(() => (inThrottle = false), limit)
    }
  }
}

const handleScroll = throttle(() => {
  // 计算滚动进度
  const scrollPercentage =
    (window.scrollY / (document.documentElement.scrollHeight - window.innerHeight)) * 100

  // 更新进度条
  if (refs.progressBar.value) {
    if (state.performance.mode === 'high') {
      gsap.to(refs.progressBar.value, {
        scaleX: scrollPercentage / 100,
        duration: 0.1,
        ease: 'none',
        overwrite: true,
      })
    } else {
      // 低性能模式下直接设置 transform
      refs.progressBar.value.style.transform = `scaleX(${scrollPercentage / 100})`
    }
  }

  // 更新返回顶部按钮状态
  state.ui.showBackToTop = window.scrollY > window.innerHeight

  // 优化内存使用
  if (state.performance.mode !== 'high') {
    performanceOptimizer.memory()
  }
}, 16)

// GSAP 动画初始化
const initAnimations = () => {
  // 遮罩动画
  ScrollTrigger.create({
    trigger: refs.heroSection.value,
    start: 'top top',
    end: '+=100%',
    pin: true,
    pinSpacing: true,
    scrub: true,
    anticipatePin: 1,
    onUpdate: (self) => {
      const progress = self.progress
      state.mask.currentScale = gsap.utils.interpolate(
        state.mask.initialScale,
        state.mask.maxScale,
        progress,
      )
      state.mask.opacity = gsap.utils.interpolate(0.92, 0.3, progress)
    },
  })

  // 视频视差效果
  gsap.to(refs.parallaxWrapper.value, {
    y: '30%',
    ease: 'none',
    scrollTrigger: {
      trigger: refs.heroSection.value,
      start: 'top top',
      end: 'bottom top',
      scrub: true,
    },
  })

  // 画廊动画
  gsap.timeline({
    scrollTrigger: {
      trigger: refs.gallerySection.value,
      start: 'top top',
      end: 'bottom bottom',
      scrub: 1,
      pin: true,
      anticipatePin: 1,
      onUpdate: (self) => {
        if (state.performance.mode === 'low') return

        const progress = self.progress
        const totalItems = state.gallery.items.length
        const currentProgress = progress * (totalItems - 0.5)

        requestAnimationFrame(() => {
          state.gallery.items.forEach((_, i) => {
            if (state.gallery.loadStatus[i]) {
              const itemProgress = gsap.utils.clamp(0, 1, currentProgress - i)
              animateGalleryItem(i, itemProgress)
            }
          })
        })
      },
      onEnter: () => {
        if (state.performance.mode === 'high') {
          gsap.fromTo(
            refs.galleryTrack.value,
            { scale: 0.8, opacity: 0 },
            { scale: 1, opacity: 1, duration: 1, ease: 'power2.out' },
          )
        }
      },
    },
  })
}

// 画廊项目动画
const animateGalleryItem = (index, progress) => {
  const image = refs.galleryImages.value[index]
  const caption = refs.galleryCaptions.value[index]

  if (!image || !caption) return

  const scale = gsap.utils.interpolate(1.1, 1, progress)
  const blur = gsap.utils.interpolate(8, 0, progress)
  const opacity = progress
  const y = gsap.utils.interpolate(50, 0, progress)

  if (state.performance.mode === 'high') {
    gsap.to(image, {
      scale,
      filter: `blur(${blur}px)`,
      opacity,
      force3D: true,
      duration: 0.5,
    })

    gsap.to(caption, {
      opacity,
      y,
      force3D: true,
      duration: 0.5,
    })
  } else {
    // 在中等性能模式下使用简单的过渡
    image.style.opacity = opacity
    image.style.transform = `scale(${scale})`
    caption.style.opacity = opacity
    caption.style.transform = `translateY(${y}px)`
  }
}

// 性能监控提示
const showPerformanceHint = (mode) => {
  const hints = {
    medium: '已切换至中等性能模式以提升流畅度',
    low: '已切换至低性能模式以确保基本功能',
  }

  if (hints[mode]) {
    const hint = document.createElement('div')
    hint.className =
      'fixed bottom-4 left-4 bg-black/80 text-white px-4 py-2 rounded-lg text-sm z-50 transition-opacity duration-300'
    hint.textContent = hints[mode]
    document.body.appendChild(hint)

    // 3秒后淡出
    gsap.to(hint, {
      opacity: 0,
      delay: 3,
      duration: 0.3,
      onComplete: () => hint.remove(),
    })
  }
}

// 优化性能降级函数

// 生命周期钩子
onMounted(() => {
  // 初始化组件
  initGallery()
  monitorPerformance()

  // 预加载视频
  if (refs.heroVideo.value) {
    refs.heroVideo.value.load()
  }

  // 添加事件监听
  window.addEventListener('scroll', handleScroll)
  window.addEventListener(
    'resize',
    () => {
      performanceOptimizer.memory()
    },
    { passive: true },
  )

  // 预加载资源
  preloadGalleryImages()

  // 初始化动画
  nextTick(() => {
    initAnimations()
  })
})

onBeforeUnmount(() => {
  // 清理事件监听
  window.removeEventListener('scroll', handleScroll)
  window.removeEventListener('resize', performanceOptimizer.memory)

  // 清理定时器和动画
  if (rafId) cancelAnimationFrame(rafId)
  ScrollTrigger.getAll().forEach((trigger) => trigger.kill())

  // 清理资源
  cleanup()
})

// 预加载画廊图片
const preloadGalleryImages = () => {
  state.gallery.items.forEach((item, index) => {
    const img = new Image()
    img.onload = () => handleImageLoad(index)
    img.src = item.url
  })
}

// 性能监控相关
let lastTime = performance.now()
let frame = 0
let rafId = null

// 性能监控
const monitorPerformance = () => {
  frame++
  const time = performance.now()
  if (time >= lastTime + 1000) {
    state.performance.fps = Math.round((frame * 1000) / (time - lastTime))
    lastTime = time
    frame = 0

    // 性能优化逻辑
    if (state.performance.fps < 30) {
      state.performance.lowPerformanceCount++
      if (state.performance.lowPerformanceCount >= 3) {
        performanceOptimizer.apply()
      }
    } else {
      state.performance.lowPerformanceCount = Math.max(0, state.performance.lowPerformanceCount - 1)
    }
  }
  rafId = requestAnimationFrame(monitorPerformance)
}

// 资源清理
const cleanup = () => {
  if (refs.heroVideo.value) {
    refs.heroVideo.value.pause()
    refs.heroVideo.value.src = ''
    refs.heroVideo.value.load()
  }

  refs.galleryImages.value.forEach((img) => {
    if (img) {
      img.src = ''
      img.srcset = ''
    }
  })
}
</script>

<style scoped>
/* 优化的样式 */
.collection-page {
  overflow-x: hidden;
}

.hero {
  position: relative;
  width: 100%;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.gallery {
  position: relative;
  background-color: black;
}

.gallery-item {
  will-change: transform, opacity;
  transform-style: preserve-3d;
  backface-visibility: hidden;
}

.gallery-item img {
  will-change: transform, filter, opacity;
  transform: scale(1.05);
  transition:
    transform 0.6s cubic-bezier(0.4, 0, 0.2, 1),
    filter 0.6s ease-out,
    opacity 0.6s ease-out;
}

.sticky-wrapper {
  perspective: 1000px;
  transform-style: preserve-3d;
}

.perspective-1000 {
  perspective: 1000px;
  transform-style: preserve-3d;
}

.caption-wrapper {
  transform-style: preserve-3d;
  will-change: transform, opacity;
  transition:
    transform 0.6s cubic-bezier(0.4, 0, 0.2, 1),
    opacity 0.6s ease-out;
}

.transform-gpu {
  transform: translateZ(0);
  backface-visibility: hidden;
  transform-style: preserve-3d;
  will-change: transform;
}

/* 降级性能时的样式 */
.reduce-motion .gallery-item img {
  transition: none !important;
}

.reduce-motion .caption-wrapper {
  transition: none !important;
}
</style>

<style>
.reduce-motion * {
  animation: none !important;
  transition: none !important;
  transform: none !important;
}

.gallery-item {
  contain: layout style paint;
  content-visibility: auto;
}

.gallery-item img {
  backface-visibility: hidden;
  transform: translateZ(0);
}

@media (prefers-reduced-motion: reduce) {
  .gallery-item {
    transition: none !important;
    transform: none !important;
  }
}

@supports not (content-visibility: auto) {
  .gallery-item {
    visibility: visible;
  }
}
</style>
